<template>
  <div class="mltcp relative   ">
    <page-loading></page-loading>
    <os-switch :item="origin.enable" v-model="enable"></os-switch>
    <div v-show="enable=='1'">
      <!-- <os-switch :item="origin.loopback" v-model="loopback"></os-switch> -->
      <os-switch :item="origin.lan" v-model="lan" v-if="lan_available"></os-switch>
      <os-switch :item="origin.wan" v-model="wan" v-if="wan_available"></os-switch>
      <os-switch item="4gwan" v-model="gwan" v-if="counter==1"></os-switch>
      <template v-for="n in counter" v-if="counter>1">
        <os-switch :item="'4gwan'+n" v-model="gwans[n-1]"></os-switch>
      </template>
    </div>
    <div class="value alone-right">
      <div class="btn btn-blue" @click="set_mptcp">{{$t('btn.save')}}</div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      origin: this.$t("service.mltcp"),
      enable: "0",
      loopback: "0",
      lan: "0",
      wan: "0",
      wan_available: true,
      lan_available: true,
      counter: 4,
      gwan: "",
      gwans: [],
    }
  },
  methods: {
    get_state() {
      this.$req.get("/webapi?op=get_mptcp_info").then(res=> {
        this.enable = res.globle_mptcp_enable
        let fields = Object.keys(res)
        this.wan_available = fields.indexOf("wan") > -1
        this.lan_available = fields.indexOf("lan") > -1
        this.wan_available ? this.wan = res.wan : ""
        this.lan_available ? this.lan = res.lan : ""
        if(fields.indexOf("4gwan")>-1) {
          this.gwan = res['4gwan']
          this.counter = 1
        } else if(fields.indexOf("4gwan1") > -1) {
          this.$set(this.gwans, 0, res['4gwan1'])
          for(let n = 2; ; n++) {
            // 也可以用res[4gwan+n]是否为undefined判断字段是否存在
            if(fields.indexOf('4gwan'+n) === -1) {
              this.counter = --n
              break
            } else {
              this.$set(this.gwans, n-1, res['4gwan'+n])
            }
          }
          console.log(this.gwans)
        } else {
          this.counter = 0
        }
      })
    },
    set_mptcp() {
      let params = {
        globle_mptcp_enable: this.enable
      }
      if(this.enable=="1") {
        this.lan_available ? params.lan = this.lan : ''
        this.wan_available ? params.wan = this.wan : ''
        if(this.counter==1) {
          params['4gwan'] = this.gwan
        } else if(this.counter>1) {
          this.gwans.forEach((item, index)=> {
            params['4gwan'+(index+1)] = item
          })
        }
      }
      console.log(params)
      this.proxy_req("post", "/webapi?op=enable_mptcp_set", params, res=> {}, )
    },
  },
  created() {
    this.$bus.emit("changeTab", 9)
    this.get_state()
  }
}
</script>

<style>
</style>
